
package com.scalar.chiptrack.operations.dataentry.actions;


import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.adaptor.InventoryLot;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.dataentry.forms.InvDataEntryForm;
import com.scalar.chiptrack.operations.dataentry.forms.InventoryDataEntryForm;
import com.scalar.chiptrack.operations.lotcorrection.dao.LotCorrectionDAO;
import com.scalar.chiptrack.operations.process.Lot;
import com.scalar.chiptrack.operations.process.ProcessStep;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.process.dao.LotDAO;
import com.scalar.chiptrack.operations.process.dao.PartNumber;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.StringUtils;


public final class InvDataEntryAction extends ChipTrackAction {

    public InvDataEntryAction() {
    }
    private static final String ACTION_NAME = "/invDataEntry.do" ;
	public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {


		ArrayList partNumberList = new ArrayList();
        HashMap info = new HashMap();
        HashMap errors = new HashMap();
		
		InvDataEntryForm invDataEntryForm = (InvDataEntryForm) form;

		HttpSession session = request.getSession(true);
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
		//added by varma 10 sep 2004
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY,  ACTION_NAME );
            return ( mapping.findForward ( "login" ) );
        }
        else
        {
            if ( user.isActionAllowed ( Functionality.DATA_ENTRY, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }
		String action =(String)request.getParameter("action");
		if(action==null || action.equals("submit"))
			action="";
        //Bhaskar added this code block on 12 December 2003
		String confirm = request.getParameter ( "confirm" );
		if ( confirm == null )
		confirm = "";

		request.setAttribute("action",action);
        if(action.equals(""))
        {
		    return (mapping.findForward("success"));
        }

        /*int prevProcessStepId=0;
        String prevLotId="";
        */

	   request.setAttribute("action",action);
        if ( invDataEntryForm.getType() != null )
        {
		    if ( invDataEntryForm.getType().equals("finished%") )
		    {
			    request.setAttribute("dateOutQtyOut", "FALSE");
		    }
		    else
		    {
			    request.setAttribute("dateOutQtyOut", "TRUE");
		    }

            partNumberList = ProductDao.getInventoryPartNumber(invDataEntryForm.getType());
        }
        PartNumber partNumber = null;
        ArrayList partNumberSelectList = new ArrayList();

        for( int i=0; i<partNumberList.size(); i++ )
        {
            partNumber = (PartNumber)partNumberList.get(i);
            String partNo = partNumber.getPartNumber();
            StringTokenizer someValue = new StringTokenizer(partNo,"/");
            String finalPartNo =  someValue.nextToken();
            partNumberSelectList.add(new LabelValueBean(finalPartNo, partNumber.getProcessStepId()+"$"+finalPartNo));
        }

        if(action.equals("type") )
        {
			invDataEntryForm.setProcessStepId("0");
            request.setAttribute("partNumberSelectList",partNumberSelectList);
            session.removeAttribute( "selectedCSIds" );
            return (mapping.findForward("success"));
        }

        if(action.equals("partnumber") || action.equals("location") || action.equals("lotnumber"))
        {
            session.removeAttribute( "selectedCSIds" );
        }
		if(action.equals("partnumber") || action.equals("location") || action.equals("lotnumber") || action.equals("save"))
        {
            request.setAttribute("partNumberSelectList",partNumberSelectList);
            String processId = invDataEntryForm.getProcessStepId();
            StringTokenizer someValuee = new StringTokenizer(processId,"$");
            String finalProcessId = someValuee.nextToken();

            ArrayList inventoryLocationList= VendorDAO.getSelectedLocations(Integer.parseInt(finalProcessId));
            ArrayList vendorLocationList = new ArrayList();
            VendorLocation vendorLocation = null;
            if(inventoryLocationList == null)
            inventoryLocationList = new ArrayList(0);

            for(int i=0;i<inventoryLocationList.size();i++)
            {
                vendorLocation=(VendorLocation)inventoryLocationList.get(i);
                vendorLocation.setLocationID(vendorLocation.getLocationID());
                vendorLocation.setLocationName(vendorLocation.getLocationName());
                String locId = new Integer(vendorLocation.getLocationID()).toString() +"$"+vendorLocation.getLocationName() ;
                vendorLocationList.add(new org.apache.struts.util.LabelValueBean(vendorLocation.getLocationName(),locId));
            }
            request.setAttribute("locationSelectList",vendorLocationList);
		}


		if(action.equals("location") || action.equals("lotnumber") || action.equals("save")  )
        {
            //StringTokenizer  someValue = null;
            String locationId = invDataEntryForm.getLocationId();
            //someValue = new StringTokenizer ( locationId, "$" );

            //String locId = someValue.nextToken ();
            //String vendorName = someValue.nextToken ();
            String processId = invDataEntryForm.getProcessStepId();
			String ps_type_name = invDataEntryForm.getType();
            //StringTokenizer someValuee = new StringTokenizer(processId,"$");
            //String finalProcessId = someValuee.nextToken();
			//Bhaskar commented the code block below and called this new private method. 10 December 2003
			ArrayList list = getLotList(processId, locationId, ps_type_name);
            /*ArrayList lotNumberList = lotDao.getRunningLotNumbers(finalProcessId,locId);
            Lot lot = null;
            java.util.ArrayList list = new java.util.ArrayList();

            if(lotNumberList == null)
	            lotNumberList = new ArrayList(0);

            for(int i=0;i<lotNumberList.size();i++)
            {
                lot =(Lot)lotNumberList.get(i);
                list.add(new org.apache.struts.util.LabelValueBean(lot.getLotNumber(),lot.getLotId()+"$"+lot.getLotNumber()+"$"+lot.getStatus()));
		    }*/
			if ( action.equalsIgnoreCase("location") )
			{
				invDataEntryForm.setLotNo("0");
			}
			request.setAttribute("lotNumbers",list);

		}

		if(action.equals("lotnumber"))
        {
			String lot 		= invDataEntryForm.getLotNo();
			if ( ( !"-1".equals ( lot ) ) )
			{
                StringTokenizer st = new StringTokenizer(lot,"$");
                String lotId			= st.nextToken();
                String lotNumber		= st.nextToken();
                String status           = st.nextToken();

				/*Bhaskar added this condt on 12 December 2003*/
				InventoryDataEntryForm inventoryLot = LotDAO.getInventoryLotData(lotId);
				String ps_type = invDataEntryForm.getType();
				if ( !ps_type.equalsIgnoreCase("fin%") )
				{

					invDataEntryForm.setQuantityIn(inventoryLot.getQuantityIn());
					invDataEntryForm.setDateIn(inventoryLot.getDateIn());
					invDataEntryForm.setDateOut("");
					invDataEntryForm.setQuantityOut("");
                    invDataEntryForm.setDateCode(inventoryLot.getDateCode());
                    invDataEntryForm.setVendorLot(inventoryLot.getVendorLot());
                    invDataEntryForm.setComments(inventoryLot.getComments());
                    invDataEntryForm.setWaferQtyIn( inventoryLot.getWaferQtyIn() );
                    invDataEntryForm.setWaferId( inventoryLot.getWaferId() );
                }
				else
				{
					invDataEntryForm.setQuantityIn(inventoryLot.getQuantityIn());
					invDataEntryForm.setQuantityOut(inventoryLot.getQuantityOut());
					invDataEntryForm.setDateIn(inventoryLot.getDateIn());
					invDataEntryForm.setDateOut(inventoryLot.getDateOut());
                    invDataEntryForm.setDateCode(inventoryLot.getDateCode());
                    invDataEntryForm.setVendorLot(inventoryLot.getVendorLot());
                    invDataEntryForm.setComments(inventoryLot.getComments());
                    invDataEntryForm.setWaferQtyIn( inventoryLot.getWaferQtyIn() );
                    invDataEntryForm.setWaferId( inventoryLot.getWaferId() );
				}
                boolean isPackingSlipLineItemsExits =  false;
                if(  !ps_type.equalsIgnoreCase("fin%") )
                {
                    invDataEntryForm.setLotId(lotId);
                    isPackingSlipLineItemsExits = LotCorrectionDAO.isLineItemsExitsByLotId( null,  lotId );
                }
                //request.setAttribute( "DisplayPSLineItemsLink", isPackingSlipLineItemsExits + "");
			}
			else
			{
				invDataEntryForm.setNewlotNo("");
				invDataEntryForm.setQuantityIn("");
				invDataEntryForm.setQuantityOut("");
				invDataEntryForm.setDateIn(StringUtils.formatDateToString(new Date(System.currentTimeMillis()), "MM/dd/yyyy"));
				invDataEntryForm.setDateOut("");
                invDataEntryForm.setDateCode("");
                invDataEntryForm.setVendorLot("");
                invDataEntryForm.setComments("");
                invDataEntryForm.setWaferQtyIn( "" );
                invDataEntryForm.setWaferId( "" );
			}
            request.setAttribute ( "lotnumber", "true" );
            request.setAttribute("invDataEntryForm",invDataEntryForm);
            return (mapping.findForward("success"));
		}


        if( "allLotInfo".equals( action ) )
        {
            String lotprocessstepId = request.getParameter("ProcessStepId");
            String lotlocationId = request.getParameter("LocationId");
            String lotNo         = request.getParameter("LotNo");

            StringTokenizer st = new StringTokenizer ( lotprocessstepId, "$" );
            String pId = st.nextToken ();
            st.nextToken ();

            st = new StringTokenizer ( lotlocationId, "$" );
            String locId = st.nextToken ();
            st.nextToken ();

            ArrayList allLotsList = null;
            try
            {
                String newlotId = LotDAO.getLotId( lotNo , locId, pId  );

                if ( newlotId != null && newlotId.length() > 0 )
                {
                    allLotsList = LotDAO.getAllLotDetails( newlotId );
                }

                request.setAttribute("allLotsList", allLotsList );

            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Error while retreiving the Lot history list", null );
            }

            return mapping.findForward( "alllotInfo" );
        }

		if(action.equals("save"))
		{
		    String lotId = null;
		    String lotNumber = null;
		    String lotStatus = null;
		    String lot = invDataEntryForm.getLotNo();
		    if ( ( !"-1".equals ( lot ) ) )
		    {
				StringTokenizer st		= new StringTokenizer(lot,"$");
				lotId			= st.nextToken();
				lotNumber		= st.nextToken();
			    lotStatus       = st.nextToken();
		    }
		    else
		    {
				lotId = "-1";
				lotNumber  = invDataEntryForm.getNewlotNo().trim();
				//invDataEntryForm.setNewlotNo("");
			}
            invDataEntryForm.setLotId(lotId);

            String processStepId	= invDataEntryForm.getProcessStepId();
		    StringTokenizer someValue = new StringTokenizer(processStepId,"$");
		    String finalProcessId   = someValue.nextToken();
		    String partNo           = someValue.nextToken();
			String dateIn			= invDataEntryForm.getDateIn();
			String dateOut			= invDataEntryForm.getDateOut();
			String quantityIn		= invDataEntryForm.getQuantityIn();
			String quantityOut		= invDataEntryForm.getQuantityOut();
			String locationId		= invDataEntryForm.getLocationId();
            String dateCode	    	= invDataEntryForm.getDateCode();
            String vendorLot    	= invDataEntryForm.getVendorLot();
            String comments	    	= invDataEntryForm.getComments();
            String waferQtyIn       = invDataEntryForm.getWaferQtyIn();
            String waferId          = invDataEntryForm.getWaferId();

			if(dateIn.equals(""))
				dateIn = null;

			if( dateOut != null )
				dateOut = dateOut.trim();

			if( quantityIn != null && quantityIn.trim().length() == 0 )
				quantityIn = null;

			if( quantityOut != null )
				quantityOut = quantityOut.trim();

            if ( waferQtyIn != null && waferQtyIn.trim().length() == 0 )
            {
                waferQtyIn = null;
            }

            if ( waferId != null && waferId.trim().length() == 0 )
            {
                waferId = null;
            }

			String type = ProcessStep.getProcessType(Integer.parseInt(finalProcessId));
		    someValue = new StringTokenizer ( locationId, "$" );
		    String locId = someValue.nextToken ();
		    String vendorName = someValue.nextToken ();
		    someValue = new StringTokenizer ( vendorName, "/" );
		    String finalVendorName = someValue.nextToken();
		    //String secondValue = someValue.nextToken();

			//check for duplication or lot number repetition. Bhaskar on 12 December 2003
			String lot_ID = LotDAO.getLotIdInDataEntry ( null, finalProcessId, locId, lotNumber );
			if(lot_ID == null) lot_ID = "";
				lot_ID = lot_ID.trim();
			if ( lotId.equals ( "-1" ) && (!confirm.equals("confirm")))
			{
				if ( "".equalsIgnoreCase(lot_ID)==false)
				{
					request.setAttribute("showError", "TRUE");
					return mapping.findForward("success");
				}
			}

			DBTransaction dbTransaction = null;
			boolean success = false;
			try
			{
				dbTransaction = DBTransaction.getInstance();
		    	dbTransaction.begin();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}

		    ArrayList inventoryLotList = new ArrayList();
		    InventoryLot inventoryLot = new  InventoryLot(finalVendorName,type);
		    inventoryLot.setPartNumber(partNo);
		    inventoryLot.setLotNumber(lotNumber);
		    inventoryLot.setDateIn(dateIn);
		    inventoryLot.setDateOut(dateOut);
		    inventoryLot.setQtyIn(quantityIn);
		    inventoryLot.setQtyOut(quantityOut);
		    inventoryLot.setType(type);
		    inventoryLot.setVendorName(finalVendorName);
            //Added by KumaraSwamy on 22nd July 2004.
		    inventoryLot.setDateCode(dateCode);
		    inventoryLot.setVendorLot(vendorLot);
            inventoryLot.setComments(comments);
            //End of additions by KumaraSwamy.

            inventoryLot.setWaferQtyIn( waferQtyIn );
            inventoryLot.setWaferId( waferId );

		    inventoryLotList.add(inventoryLot);

            //Added by KumaraSwamy on Nov18th, 2004.
            String[] selectedCsIds = ( String[] ) session.getAttribute( "selectedCSIds" );
            int totCslntQtyShipped = 0;
            int selectedCsIdsLength = 0;
            int qtyIn = 0;
            int qtyPulled = 0;
            boolean save = true;

            if( selectedCsIds != null )
            {
                selectedCsIdsLength = selectedCsIds.length;
            }
            for(int i = 0; i < selectedCsIdsLength; i++ )
            {
                int cslntQtyShipped = 0;
                cslntQtyShipped = LotDAO.getCSLNTQuantityShiped (dbTransaction, selectedCsIds[i] );
                totCslntQtyShipped = totCslntQtyShipped + cslntQtyShipped;
            }

            qtyPulled = LotDAO.getCSLNTQuantityPulled (dbTransaction, lotId );
            qtyPulled = (qtyPulled - totCslntQtyShipped);

            try{
                qtyIn = Integer.parseInt( quantityIn );
            }
            catch(Exception e){}
            if( qtyIn < qtyPulled )
            {
                invDataEntryForm.setLotId(lotId);
                errors.put ( "Quantity In should not be less than Packing Slip Issued quantity ( "+ qtyPulled +" )", null);
                request.setAttribute( SessionKeys.ERROR_MESSAGES , errors );
                boolean isPackingSlipLineItemsExits =  false;
                isPackingSlipLineItemsExits = LotCorrectionDAO.isLineItemsExitsByLotId( dbTransaction,  lotId );
                request.setAttribute( "DisplayPSLineItemsLink", isPackingSlipLineItemsExits + "");
                save = false;
            }
            /* boolean isPackingSlipLineItemsExits =  false;
             isPackingSlipLineItemsExits = LotCorrectionDAO.isLineItemsExitsByLotId( dbTransaction,  lotId );
             request.setAttribute( "DisplayPSLineItemsLink", isPackingSlipLineItemsExits + "");*/
            if( save )
            {
			/*This method is called by Bhaskar  and is added on 08 December  2003.
			 * To update the lot_current_status to close from running. This will be
			 * called in all DataEntry classes just before actual create or updation
			 * concept. Even if a lotId of -1 is passed still the procedure will execute
			 * successfully
			 */
                LotDAO.changeLotStatusToCloseByLotId(dbTransaction, lotId);

                if( confirm.equals("confirm") )
                {
                    LotDAO.updateLotStatus(dbTransaction, Integer.parseInt( lot_ID ), confirm );
                }

                LotDAO.saveInventoryLot(dbTransaction,inventoryLotList.iterator(),"","");

                //PACKINGSLIP CANCELLENTATION STARTS FROM HERE

                String ps_type = invDataEntryForm.getType();
                if( !ps_type.equalsIgnoreCase("fin%") && selectedCsIds != null && selectedCsIds.length > 0 )
                {
                    LotCorrectionDAO.cancelPackingSlips( dbTransaction , selectedCsIds, lotId );

                    //System.out.println("<<<<<<<<<<<<PACKINGS CANCELLED SUCESSFULLY>>>>>>>>>>>");
                }
                //PACKINGSLIP CANCELLENTATION END FROM HERE
                /*isPackingSlipLineItemsExits =  false;
                isPackingSlipLineItemsExits = LotCorrectionDAO.isLineItemsExitsByLotId( dbTransaction, lotId );
                request.setAttribute( "DisplayPSLineItemsLink", isPackingSlipLineItemsExits + "");*/
                success	= true;
            }
		    if(success == true)
		    {
		        info.put( "Data has been updated successfully ", null);
		        request.setAttribute( SessionKeys.INFO_MESSAGES, info );
		    }

			try
			{
				if(success==true)
					dbTransaction.commit();
				else
					dbTransaction.rollback();
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
			}


            String processId = invDataEntryForm.getProcessStepId();
			String ps_type_name = invDataEntryForm.getType();
			ArrayList lotList = getLotList(processStepId, locationId, ps_type_name);
			String latestLotNum = returnLatestLotNumber(lotList, lotNumber);
		    if(lot.equals("-1"))
		    {
				invDataEntryForm.setNewlotNo("");

				if ( quantityOut != null && quantityOut.trim().length() > 0 )
				{
					int qIn  = 0;
                    try
                    {
                        if ( ps_type_name.startsWith( "wafer" ) )
                        {
                            qIn = Integer.parseInt(waferQtyIn);
                        }
                        else
                        {
                            qIn = Integer.parseInt(quantityIn);
                        }
                    }catch( Exception e ){}
					int qOut = Integer.parseInt(quantityOut);
					if ( ( qIn - qOut ) > 0 )
					{
						invDataEntryForm.setLotNo(latestLotNum);
                        if ( ps_type_name.startsWith( "wafer" ) )
                        {
                            invDataEntryForm.setWaferQtyIn(""+( qIn - qOut ));
                        }
                        else
                        {
						    invDataEntryForm.setQuantityIn(""+( qIn - qOut ));
                        }
						invDataEntryForm.setQuantityOut("");
						invDataEntryForm.setDateOut("");
					}
					else
					{
						invDataEntryForm.setLotNo("0");
						invDataEntryForm.setQuantityIn("");
                        invDataEntryForm.setWaferQtyIn( "" );
                        invDataEntryForm.setWaferId( "" );
						invDataEntryForm.setDateOut("");
						invDataEntryForm.setQuantityOut("");
						invDataEntryForm.setDateIn("");
					}
			    }
			    else
			    {
					invDataEntryForm.setLotNo(latestLotNum);
			    }
		        request.setAttribute("lotNumbers",lotList);
		    }
			else
		    {

				/*Bhaskar added this condt on 12 December 2003*/
				InventoryDataEntryForm inventoryLot1 = LotDAO.getInventoryLotData(lotId);
				String ps_type = invDataEntryForm.getType();
				if ( quantityOut != null && quantityOut.trim().length() > 0 )
				{
					int qIn  = 0;
                    try
                    {
                        if ( ps_type_name.startsWith( "wafer" ) )
                        {
                            qIn = Integer.parseInt(waferQtyIn);
                        }
                        else
                        {
                            qIn = Integer.parseInt(quantityIn);
                        }
                    }
                    catch ( Exception e) { }
					int qOut = Integer.parseInt(quantityOut);
					if ( ( qIn - qOut ) > 0 )
					{
						invDataEntryForm.setLotNo( lot );
                        if ( ps_type_name.startsWith( "wafer" ) )
                        {
                            invDataEntryForm.setWaferQtyIn(""+( qIn - qOut ));
                        }
                        else
                        {
						    invDataEntryForm.setQuantityIn(""+( qIn - qOut ));
                        }
						invDataEntryForm.setQuantityOut("");
						invDataEntryForm.setDateOut("");
					}
					else
					{
						invDataEntryForm.setLotNo("0");
						invDataEntryForm.setQuantityIn("");
						invDataEntryForm.setQuantityOut("");
						invDataEntryForm.setDateOut("");
						invDataEntryForm.setDateIn("");
                        invDataEntryForm.setWaferQtyIn( "" );
                        invDataEntryForm.setWaferId( "" );
					}
				}
				else
				{
					invDataEntryForm.setLotNo(lot);
				}
				request.setAttribute("lotNumbers",lotList);
		    }
		    request.setAttribute("invDataEntryForm",invDataEntryForm);
		}
		return (mapping.findForward("success") );
    }

	/**
	Method added by Bhaskar on 10 December 2003 to get the Lot Numbers for WS, DB, CS, FG
	*/
    private ArrayList getLotList(String processStepId, String locationId, String psType_name)
    {
        java.util.ArrayList list = new ArrayList();
		try
        {
            StringTokenizer st = new StringTokenizer ( processStepId, "$" );
            String pId = st.nextToken ();

            st = new StringTokenizer ( locationId, "$" );
            String locId = st.nextToken ();

            ArrayList lotNumberList = LotDAO.getRunningLotNumbersByPSTypeName ( pId, locId, psType_name.substring(0, psType_name.length()-1));

			Lot lot = null;
            list = new java.util.ArrayList ();

            for ( int i = 0; i < lotNumberList.size (); i++ )
            {
                lot = ( Lot ) lotNumberList.get ( i );
                list.add ( new LabelValueBean ( lot.getLotNumber (), lot.getLotId () + "$" + lot.getLotNumber () + "$" + lot.getStatus () ) );
            }
        }
        catch(Exception e)
        {
			System.out.println ("DataEntryForAllProcessStepsAction class : "+e.getMessage());
        }
        return list;
    }


	private String returnLatestLotNumber ( ArrayList lotList, String latestLotNumber )
	{
		String latestLotNumberDefault = "-1";
		for (int count=0; count < lotList.size(); count++)
		{
			LabelValueBean labelValueBean = (LabelValueBean)lotList.get(count);

			if (labelValueBean.getLabel().equals(latestLotNumber.trim()))
			{
				latestLotNumberDefault = labelValueBean.getValue();
				break;
			}
		}
		return latestLotNumberDefault.trim();
	}
}